package com.socool.sinofaith.ui;

import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import com.deying.actionbarcompat.ActionBarHelperBase;
import com.deying.actionbarcompat.ActionBarHelperBase.CenterViewFactory;
import com.deying.actionbarcompat.ActionBarHelperBase.SpinnerViewFactory;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.adapter.MyAdapter;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.BaseMessage;
import com.socool.sinofaith.model.MyListItem;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.DBManager;
import com.socool.sinofaith.util.SinofaithUtil;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends BaseActivity implements
		CenterViewFactory, SpinnerViewFactory, View.OnClickListener {

	private Button registerButton;
	ActionBarHelperBase mActionBarHelperBase;
	private EditText phoneEditText, userNameEditText, passwordEditText,
			retrypasswordEditText, CustomCode;
	private Spinner spinner1, spinner2;
	private String province = "北京市";
	private String city = "北京市";
	private String Sex = "男";

	private DBManager dbm;
	private SQLiteDatabase db;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		SocoolApplication.addActivity(this);
		mActionBarHelperBase = (ActionBarHelperBase) this.getActionBarHelper();
		mActionBarHelperBase.setmCenterViewFactory(this);
		mActionBarHelperBase.setmSpinnerViewFactory(this);
		mActionBarHelperBase.setmClickListener(this);
		registerButton = (Button) findViewById(R.id.registerButton);
		phoneEditText = (EditText) findViewById(R.id.phoneEditText);
		userNameEditText = (EditText) findViewById(R.id.userNameEditText);
		passwordEditText = (EditText) findViewById(R.id.passwordEditText);
		retrypasswordEditText = (EditText) findViewById(R.id.retrypasswordEditText);
		CustomCode = (EditText) findViewById(R.id.CustomCode);
		registerButton.setOnClickListener(this);

		spinner1 = (Spinner) findViewById(R.id.province);
		spinner2 = (Spinner) findViewById(R.id.city);
		initSpinner1();

		// 根据ID找到RadioGroup实例
		RadioGroup group = (RadioGroup) this.findViewById(R.id.radioGroup);
		// 绑定一个匿名监听器
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				// TODO Auto-generated method stub
				// 获取变更后的选中项的ID
				int radioButtonId = arg0.getCheckedRadioButtonId();
				// 根据ID获取RadioButton的实例
				RadioButton rb = (RadioButton) RegisterActivity.this
						.findViewById(radioButtonId);
				// 更新文本内容，以符合选中项
				Sex = rb.getText().toString();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.common, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public View createView() {

		TextView tv = new TextView(this);
		tv.setText("注册");
		tv.setTextColor(this.getResources().getColor(R.color.white));
		tv.setTextSize(20);
		return tv;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated
															// method stub
		if (item.getItemId() == R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public View createSpinnerView() {
		TextView tv = new TextView(this);
		return tv;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {

		case R.id.registerButton:

			if (isReadyRegister()) {
				FinalHttp fh = new FinalHttp();
				AjaxParams params = new AjaxParams();
				params.put("sid", ConstansJsonUrl.register_url);
				params.put("did", SinofaithUtil.did);
				params.put("ucode", SinofaithUtil.getDeviceID(this));
				params.put("Mobile", phoneEditText.getText().toString());
				params.put("Name", userNameEditText.getText().toString());
				params.put("Pwd", SinofaithUtil.md5(passwordEditText.getText()
						.toString()));
				params.put("CustomCode", CustomCode.getText().toString());
				params.put("Sex", Sex);
				params.put("Pro", province);
				params.put("City", city);
				Log.v("qqqq", ConstansJsonUrl.REQUEST_URL+"/"+params);
				fh.post(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {
					@Override
					public void onLoading(long count, long current) {
						// TODO Auto-generated method stub
						super.onLoading(count, current);
					}

					@Override
					public void onSuccess(Object t) {
						// TODO Auto-generated method stub
						super.onSuccess(t);
						try {
							BaseMessage baseMessage = HttpJsonAdapter
									.getInstance().get(t.toString(),
											BaseMessage.class);
							if (baseMessage.getResult().equals("0")) {
								Toast.makeText(RegisterActivity.this,
										baseMessage.getDesc(),
										Toast.LENGTH_LONG).show();
								SharedPreferences preferences = getSharedPreferences(
										"login", MODE_PRIVATE);
								Editor editor = preferences.edit();
								editor.putString("userName", phoneEditText
										.getText().toString());
								editor.putString("password", passwordEditText
										.getText().toString());
								editor.putBoolean("remember", true);
								editor.commit();
								RegisterActivity.this.finish();

							} else {
								Toast.makeText(RegisterActivity.this,
										baseMessage.getDesc(),
										Toast.LENGTH_LONG).show();

							}
						} catch (Exception e) {
							Toast.makeText(RegisterActivity.this,
									e.getMessage(), Toast.LENGTH_LONG).show();
						}
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						// TODO Auto-generated method stub
						super.onFailure(t, errorNo, strMsg);
						Toast.makeText(RegisterActivity.this, strMsg,
								Toast.LENGTH_LONG).show();
					}

				});
			}
			break;

		}
	}

	boolean isReadyRegister() {

		if (TextUtils.isEmpty(phoneEditText.getText())) {
			Toast.makeText(this, "请输入您的手机号码！", Toast.LENGTH_SHORT).show();
			return false;
		}
		String telRegex = "[1][3578]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
		if (!phoneEditText.getText().toString().matches(telRegex)) {
			Toast.makeText(this, "请输入正确的手机号码！！", Toast.LENGTH_SHORT).show();
			return false;
		}

		if (TextUtils.isEmpty(userNameEditText.getText())) {
			Toast.makeText(this, "请输入您的姓名！", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(passwordEditText.getText())) {
			Toast.makeText(this, "请输入您的密码！", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(retrypasswordEditText.getText())) {
			Toast.makeText(this, "请再次输入您的密码！", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (!passwordEditText.getText().toString()
				.equals(retrypasswordEditText.getText().toString())) {
			Toast.makeText(this, "两次密码输入不一致", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	// 省市区级联
	public void initSpinner1() {
		dbm = new DBManager(this);
		dbm.openDatabase();
		db = dbm.getDatabase();
		List<MyListItem> list = new ArrayList<MyListItem>();
		try {
			String sql = "select * from province";
			Cursor cursor = db.rawQuery(sql, null);
			cursor.moveToFirst();
			while (!cursor.isLast()) {
				String code = cursor.getString(cursor.getColumnIndex("code"));
				byte bytes[] = cursor.getBlob(2);
				String name = new String(bytes, "gbk");
				MyListItem myListItem = new MyListItem();
				myListItem.setName(name);
				myListItem.setPcode(code);
				list.add(myListItem);
				cursor.moveToNext();
			}
			String code = cursor.getString(cursor.getColumnIndex("code"));
			byte bytes[] = cursor.getBlob(2);
			String name = new String(bytes, "gbk");
			MyListItem myListItem = new MyListItem();
			myListItem.setName(name);
			myListItem.setPcode(code);
			list.add(myListItem);
		} catch (Exception e) {
		}
		db.close();
		dbm.closeDatabase();
		MyAdapter myAdapter = new MyAdapter(this, list);
		spinner1.setAdapter(myAdapter);
		spinner1.setOnItemSelectedListener(new SpinnerOnSelectedListener1());
	}

	public void initSpinner2(String pcode) {
		dbm = new DBManager(this);
		dbm.openDatabase();
		db = dbm.getDatabase();
		List<MyListItem> list = new ArrayList<MyListItem>();
		try {
			String sql = "select * from city where pcode='" + pcode + "'";
			Cursor cursor = db.rawQuery(sql, null);
			cursor.moveToFirst();
			while (!cursor.isLast()) {
				String code = cursor.getString(cursor.getColumnIndex("code"));
				byte bytes[] = cursor.getBlob(2);
				String name = new String(bytes, "gbk");
				MyListItem myListItem = new MyListItem();
				myListItem.setName(name);
				myListItem.setPcode(code);
				list.add(myListItem);
				cursor.moveToNext();
			}
			String code = cursor.getString(cursor.getColumnIndex("code"));
			byte bytes[] = cursor.getBlob(2);
			String name = new String(bytes, "gbk");
			MyListItem myListItem = new MyListItem();
			myListItem.setName(name);
			myListItem.setPcode(code);
			list.add(myListItem);
		} catch (Exception e) {
		}
		db.close();
		dbm.closeDatabase();
		MyAdapter myAdapter = new MyAdapter(this, list);
		spinner2.setAdapter(myAdapter);
		spinner2.setOnItemSelectedListener(new SpinnerOnSelectedListener2());
	}

	class SpinnerOnSelectedListener1 implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> adapterView, View view,
				int position, long id) {
			province = ((MyListItem) adapterView.getItemAtPosition(position))
					.getName();
			String pcode = ((MyListItem) adapterView
					.getItemAtPosition(position)).getPcode();
			initSpinner2(pcode);
		}

		public void onNothingSelected(AdapterView<?> adapterView) {
		}
	}

	class SpinnerOnSelectedListener2 implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> adapterView, View view,
				int position, long id) {
			city = ((MyListItem) adapterView.getItemAtPosition(position))
					.getName();
		}

		public void onNothingSelected(AdapterView<?> adapterView) {
		}
	}

}
